package com.beerbear.jwt.Handler;

import com.beerbear.jwt.Context.UserContext;
import com.beerbear.jwt.Entity.User;
import com.beerbear.jwt.Util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 简单的白名单，登录这个接口直接放行
        if ("/login".equals(request.getRequestURI())) {
            return true;
        }

        // 从请求头中获取token字符串并解析
        Claims claims = JwtUtil.parse(request.getHeader("Authorization"));
        // 已登录就直接放行
        if (claims != null) {
            String userName = claims.getSubject();
            User user = findUserByUserName(userName);
            // 将用户信息放到上下文中，每次都要放进来，因为Tomcat的线程是可复用的，很有可能当前线程的user是上一次别人添加的user信息
            UserContext.add(user);
            return true;
        }

        // 走到这里就代表是其他接口，且没有登录
        // 设置响应数据类型为json（前后端分离）
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        // 设置响应内容，结束请求
        out.write("请先登录");
        out.flush();
        out.close();
        return false;
    }

    /**
     * create by: Beer Bear
     * description: 模拟根据用户名查询数据库找到用户所有信息
     * create time: 2021/9/12 11:46
     */
    private User findUserByUserName(String userName) {
        User user = new User();
        if(userName.equals("admin")){
            user.setUsername(userName);
            user.setPassword("admin");
        }
        return user;
    }
}
